package han.message;

import com.han.http.client.method.HttpPost;
import com.han.http.client.paramter.FormDataPair;
import com.han.http.client.paramter.RequestHeader;
import com.han.http.fetch.Fetcher;
import han.entity.ContentEntity;
import han.entity.FontEntity;
import han.entity.GroupEntity;
import han.entity.GroupMemberEntity;
import han.parser.GroupParser;
import han.proof.SmartqqProof;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author: Han
 * @date: 2018/7/11 13:46
 * @dscription: 群管理
 */
public class GroupManager {

    private static Logger logger = LoggerFactory.getLogger(GroupManager.class);

    /**
     * 向指定群发送信息
     *
     * @param content 内容
     * @throws Exception 抛出异常
     */
    public static void sendToGroup(long groupUin, String content) throws Exception {
        SmartqqProof smartqqProof = SmartqqProof.getInstance();
        String cookie = smartqqProof.getCookie().replaceAll("; uin=[o]?", "; uin=o");
        String psessionid = smartqqProof.getPsessionid();
        String urlStr = "http://d1.web2.qq.com/channel/send_qun_msg2";
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "d1.web2.qq.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("Content-Length", "632"),
                new RequestHeader("Origin", "http://d1.web2.qq.com"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36"),
                new RequestHeader("Content-Type", "application/x-www-form-urlencoded"),
                new RequestHeader("Accept", "*/*"),
                new RequestHeader("Referer", "http://d1.web2.qq.com/cfproxy.html?v=20151105001&callback=1"),
                new RequestHeader("Accept-Encoding", "gzip, deflate"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", cookie)
        };
        ContentEntity contentEntity = new ContentEntity(new FontEntity(), content);
        FormDataPair[] formDataPairs = {
                new FormDataPair("r", "{\"group_uin\":" + groupUin + ",\"content\":" + contentEntity + "\",\"face\":555," +
                        "\"clientid\":53999199,\"msg_id\":8680005,\"psessionid\":\"" + psessionid + "\"}")
        };
        int generalTimeout = 1000 * 10;
        Fetcher fetcher = new Fetcher();
        fetcher.getPageInfoByPost(urlStr, requestHeaders, formDataPairs, generalTimeout, generalTimeout, false, HttpPost.UTF_8, null);
    }

    /**
     * 获取群列表
     *
     * @return 群
     * @throws Exception 抛出异常
     */
    public List<GroupEntity> getGroupList() throws Exception {

        Fetcher fetcher = new Fetcher();

        SmartqqProof smartqqProof = SmartqqProof.getInstance();
        String cookie = smartqqProof.getCookie();
        String vfwebqq = smartqqProof.getVfwebqq();
        String hash = smartqqProof.getHash();

        String urlStr = "https://s.web2.qq.com/api/get_group_name_list_mask2";
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "s.web2.qq.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("Content-Length", "148"),
                new RequestHeader("Origin", "https://s.web2.qq.com"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36"),
                new RequestHeader("Content-Type", "application/x-www-form-urlencoded"),
                new RequestHeader("Accept", "*/*"),
                new RequestHeader("Referer", "https://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1"),
                new RequestHeader("Accept-Encoding", "gzip, deflate"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", cookie)
        };
        FormDataPair[] formDataPairs = {
                new FormDataPair("r", "{\"vfwebqq\":\"" + vfwebqq + "\",\"hash\":\"" + hash + "\"}")
        };

        int generalTimeout = 1000 * 10;
        String groupStr = fetcher.getPageInfoByPost(urlStr, requestHeaders, formDataPairs, generalTimeout,
                generalTimeout, false, HttpPost.UTF_8, null);

        List<GroupEntity> groupList = GroupParser.getGroupNameFromSmartqq(groupStr);
        Random random = new Random();
        int interval;
        for (GroupEntity entity : groupList) {
            interval = random.nextInt(1000 * 2) + 1000 * 2;
            Map<String, GroupMemberEntity> groupMemberMap = new HashMap<>(10);
            try {
                try {
                    //使用gid获取群成员信息
                    long gCode = entity.getCode();
                    groupMemberMap.putAll(getGroupInfo(gCode));
                } catch (Exception e) {
                    //如果使用gid未获取群成员信息,则使用code获取群成员信息
                    long gCode = entity.getGid();
                    groupMemberMap.putAll(getGroupInfo(gCode));
                }
            } catch (Exception e) {
                logger.error(entity + "获取群成员失败");
                logger.info(e.toString());
                StackTraceElement[] stackTraceElements = e.getStackTrace();
                for (StackTraceElement stackTraceElement : stackTraceElements) {
                    logger.error(stackTraceElement.toString());
                }
            } finally {
                entity.setMemberMap(groupMemberMap);
                try {
                    //不管成功失败,都会休眠
                    Thread.sleep(interval);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        //解析出群组list,并返回
        return groupList;
    }

    /**
     * 获取群组详细信息
     *
     * @throws Exception 抛出异常
     */
    private Map<String, GroupMemberEntity> getGroupInfo(long gCode) throws Exception {
        SmartqqProof smartqqProof = SmartqqProof.getInstance();
        String url = "https://s.web2.qq.com/api/get_group_info_ext2?gcode=" + gCode + "&vfwebqq="
                + smartqqProof.getVfwebqq() + "&t=" + System.currentTimeMillis();
        String cookie = smartqqProof.getCookie().replaceAll("; uin=[o]?", "; uin=o");
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "s.web2.qq.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36"),
                new RequestHeader("Content-Type", "utf-8"),
                new RequestHeader("Accept", "*/*"),
                new RequestHeader("Referer", "https://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1"),
                new RequestHeader("Accept-Encoding", "gzip, deflate"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", cookie)
        };
        Fetcher fetcher = new Fetcher();
        int generalTimeout = 1000 * 30;
        String page = fetcher.getPageInfoByGet(url, requestHeaders, generalTimeout, generalTimeout, false, null);

        return GroupParser.getGroupMemberMapFromSmartqq(page);
    }
}
